package Fragment;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;

import www.truongnha.com.R;
import Config.setting;
import TruongNhaLib.Attend;
import TruongNhaLib.AttendAdapter;
import TruongNhaLib.JSONParser;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

public class AttendanceFragment extends Fragment {
	private static String host = setting.getHost();
	private static String url_getAttendanceForStudent_allYear = host
			+ "api/getAttendanceForStudent/allYear";
	private static String url_getAttendanceForStudent_allTerm = host
			+ "api/getAttendanceForStudent/allTerm";
	private Intent doneLoading;
	private List<Attend> list = new ArrayList<Attend>();
	// private List<Attend> list_all_year;
	// private List<Attend> list_all_term;
	private AttendAdapter attendAdapter;

	private ListView grid;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.attendance_fragment, container,
				false);
		new getAttendanceTask().execute(url_getAttendanceForStudent_allYear);
		grid = (ListView) view.findViewById(R.id.attendance_grid);
		attendAdapter = new AttendAdapter(getActivity(), list);
		grid.setAdapter(attendAdapter);
		return view;
	}

	class getAttendanceTask extends AsyncTask<String, Void, Void> {
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			doneLoading = new Intent();
			doneLoading.setAction("DONE_LOADING_ACTION");
			doneLoading.putExtra("doneLoading", false);
			getActivity().getApplicationContext().sendBroadcast(doneLoading);
		}

		@Override
		protected Void doInBackground(String... params) {
			JSONArray attend_array = new JSONParser().getJSONArray(params[0]);
			int size = attend_array.length();
			list.clear();
			try {
				for (int i = 0; i < size; i++) {
					Attend attend = new Attend(attend_array.getJSONObject(i));
					list.add(attend);
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			// Broadcast to main activity when done loading
			doneLoading = new Intent();
			doneLoading.setAction("DONE_LOADING_ACTION");
			doneLoading.putExtra("doneLoading", true);
			getActivity().getApplicationContext().sendBroadcast(doneLoading);
			attendAdapter.notifyDataSetChanged();
			// grid.smoothScrollToPosition(list.size());
		}
	}// End class getTermTask

}
